package com.da.javatest.thread.juc.base;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author JokerDa.
 * @date 2021/7/7 15:32
 * Description:
 */
public class ThreadDemo2 {
    private int number = 0;
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void incr() throws InterruptedException {
        try {
            lock.lock();
            while (number != 0) {
                condition.await();
            }

            // 如果number为0则+1
            number++;
            System.out.println(Thread.currentThread().getName() + "::" + number);

            // 通知其他线程
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void decr() throws InterruptedException {
        try {
            lock.lock();
            while (number != 1) {
                condition.await();
            }

            // 如果number为0则-1
            number--;
            System.out.println(Thread.currentThread().getName() + "::" + number);

            // 通知其他线程
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ThreadDemo2 share = new ThreadDemo2();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "DD").start();
    }
}

